﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyTiemThuocTay.cls;
using QuanLyTiemThuocTay.Report;
using QuanLyTiemThuocTay.GiaoDien;

namespace QuanLyTiemThuocTay.GUI
{
    public partial class frmPhieuXuat : DevExpress.XtraEditors.XtraForm
    {
        bool banbuon = true;
        public frmPhieuXuat(bool banbuon)
        {
            InitializeComponent();
            GridLocalizer.Active = new GridLocalizer();
            btIn.Enabled = false;
           this.banbuon = banbuon;
           if (banbuon)
           {
               Text = "Hóa đơn bán buôn";
               leGiaThuoc.DisplayMember = "GiaBanBuon";
           }
           else
           {
               Text = "Hóa đơn bán lẻ";
               leGiaThuoc.DisplayMember = "GiaBanLe";
           }
        }

        QLTTDataContext db = new QLTTDataContext();
        private int indexdongmoi;
        private int indexdongcu;
        List<CHITIETXUATDVT> ctxs;
        private KHACHHANG khachhang;
        private void frmPhieuNhap_Load(object sender, EventArgs e)
        {
            btLuu.Enabled = true;
            btXoa.Enabled = btSua.Enabled = false;
            leTenThuoc.DataSource = seThuoc.Properties.DataSource = new BindingList<THUOC>(db.THUOCs.ToList());
            leDVT.DataSource = new BindingList<DVTINH>(db.DVTINHs.ToList());
            leGiaThuoc.DataSource = new BindingList<GIATHUOC>(db.GIATHUOCs.ToList());
            cbbKhachHang.Properties.DataSource = new BindingList<KHACHHANG>(db.KHACHHANGs.ToList());
            dtNgayLapPhieu.EditValue = DateTime.Now;
            ctxs = new List<CHITIETXUATDVT>();
            tbSoPhieu.Text = TaoSoPhieu();
        }

        private string TaoSoPhieu()
        {
            string str = "";
            if (banbuon)
            {
                var ob = db.HDXUATs.Where(x => x.SoHDXuat.StartsWith("BB")).ToList();
                if (ob.Count > 0)
                {
                    int code = Int32.Parse(ob.Last().SoHDXuat.Substring(2, ob.Last().SoHDXuat.Length - 2));
                    HDXUAT hd = null;
                    do
                    {
                        code++;
                        if (code < 10)
                            str = "BB0000" + code;
                        else if (code < 100)
                            str = "BB000" + code;
                        else if (code < 1000)
                            str = "BB00" + code;
                        else if (code < 10000)
                            str = "BB0" + code;
                        else str = "BB" + code;
                        hd = db.HDXUATs.SingleOrDefault(x => x.SoHDXuat == str);
                    } while (hd != null);
                    return str;
                }
                else
                    return "BB00001";
            }
            else
            {
                var ob = db.HDXUATs.Where(x => x.SoHDXuat.StartsWith("BL")).ToList();
                if (ob.Count > 0)
                {
                    int code = Int32.Parse(ob.Last().SoHDXuat.Substring(2, ob.Last().SoHDXuat.Length - 2));
                    HDXUAT hd = null;
                    do
                    {
                        code++;
                        if (code < 10)
                            str = "BL0000" + code;
                        else if (code < 100)
                            str = "BL000" + code;
                        else if (code < 1000)
                            str = "BL00" + code;
                        else if (code < 10000)
                            str = "BL0" + code;
                        else str = "BL" + code;
                        hd = db.HDXUATs.SingleOrDefault(x => x.SoHDXuat == str);
                    } while (hd != null);
                    return str;
                }
                else
                    return "BL00001";
            }
        }

        private void btMoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tbSoPhieu.Text = TaoSoPhieu();
            btSua.Enabled = btXoa.Enabled = btIn.Enabled = false;
            btLuu.Enabled = true;
            cbbKhachHang.ShowPopup();
        }

        private void leKhachHang_AddNewValue(object sender, DevExpress.XtraEditors.Controls.AddNewValueEventArgs e)
        {

        }

        private void btDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        private void btMo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            btLuu.Enabled = false;
            btSua.Enabled = btXoa.Enabled = btIn.Enabled = true;
            clsHam.returnvalueinputbox = "";
            frmInput ip = new frmInput("Nhập giá trị", "Nhập số phiếu cần mở:");
            ip.ShowDialog();
            if (clsHam.returnvalueinputbox.Trim().Length > 0 )
            {
                if (banbuon)
                {
                    if (clsHam.returnvalueinputbox.Trim().StartsWith("BL")) 
                        return;
                }
                else
                {
                    if (clsHam.returnvalueinputbox.Trim().StartsWith("BB")) 
                        return;
                }
                HDXUAT hdx = db.HDXUATs.SingleOrDefault(x => x.SoHDXuat == clsHam.returnvalueinputbox);
                if (hdx != null)
                {
                    tbSoPhieu.Text = hdx.SoHDXuat;
                    var kh = db.KHACHHANGs.SingleOrDefault(x => x.TenKH == hdx.XuatChoDonVi);
                    if (kh != null)
                        cbbKhachHang.EditValue = kh.MaKH;
                    else
                    {
                        cbbKhachHang.Text = "Đã xóa khách hàng này ra khỏi hệ thống";
                        tbDiaChi.Text = "Đã xóa khách hàng này ra khỏi hệ thống";
                    }
                    var lctx = db.CHITIETXUATs.Where(x => x.SoHDXuat == hdx.SoHDXuat).ToList();
                    List<CHITIETXUATDVT> lctxdvt = new List<CHITIETXUATDVT>();
                    foreach (var item in lctx)
                    {
                        CHITIETXUATDVT te = new CHITIETXUATDVT();
                        te.MaChiTiet = item.MaChiTiet;
                        te.MaDonGia = item.MaDonGia;
                        te.DonViTinh = db.THUOCs.Single(x => x.MaThuoc == item.MaThuoc).DVTINH.TenDVTinh;
                        te.MaThuoc = item.MaThuoc;
                        te.SoHDXuat = hdx.SoHDXuat;
                        te.SoLuong = item.SoLuong;
                        lctxdvt.Add(te);
                    }
                    gc.DataSource = null;
                    gc.RefreshDataSource();
                    gc.DataSource = lctxdvt;
                    gc.RefreshDataSource();
                }
                else
                    clsHam.HienThi(Text, "Không có phiếu xuất nào phù hợp với số phiếu này: " + clsHam.returnvalueinputbox);
            }
        }

        private void gv_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.SetRowCellValue(e.RowHandle, view.Columns["SoHDXuat"], tbSoPhieu.Text);
        }

        private void gv_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            (sender as GridView).ShowEditor();
        }

        private void gv_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            indexdongcu = e.PrevFocusedRowHandle;
            indexdongmoi = e.FocusedRowHandle;
            gv.SetRowCellValue(indexdongmoi, gv.Columns["SoHDXuat"], tbSoPhieu.Text);
            var temp = gv.GetFocusedRow() as CHITIETXUATDVT;
            spSoLuong.MaxValue = soLuongConCuaThuoc(temp.MaThuoc);
        }

        private void btXoaRow_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            gv.DeleteRow(gv.FocusedRowHandle);
        }

        int ThanhTien(string soluong, string dongia)
        {
            int sl = 0;
            int dg = 0;
            if (Int32.TryParse(soluong, out sl) && Int32.TryParse(dongia, out dg))
                return sl * dg;
            else
                return 0;
        }

        private void seThuoc_EditValueChanged(object sender, EventArgs e)
        {
            if (tbSoPhieu.Text.Trim().Length > 0)
            {
                try
                {
                    List<GIATHUOC> giathuocs = db.GIATHUOCs.Where(x => x.MaThuoc == seThuoc.EditValue.ToString()).ToList();
                    if (giathuocs.Count > 0)
                    {
                        CHITIETXUATDVT ctx = new CHITIETXUATDVT();
                        ctx.MaDonGia = giathuocs.Last().MaDonGia;
                        ctx.MaThuoc = seThuoc.EditValue.ToString();
                        ctx.DonViTinh = db.THUOCs.Single(x => x.MaThuoc == ctx.MaThuoc).DVTINH.TenDVTinh;
                        ctx.SoHDXuat = tbSoPhieu.Text;
                        var soluong = soLuongConCuaThuoc(ctx.MaThuoc);
                        if (soluong==0)
                        {
                            clsHam.HienThi(Text, "Thuốc/thiết bị này đã hết trong kho thuốc");
                            return;
                        }
                        else
                        {
                            spSoLuong.MaxValue = soLuongConCuaThuoc(ctx.MaThuoc);
                        }
                        ctx.SoLuong = 1;
                        if (banbuon)
                            ctx.ThanhTien = giathuocs.Last().GiaBanBuon;
                        else 
                            ctx.ThanhTien = giathuocs.Last().GiaBanLe;
                        bool datontaitrongds = false;
                        for (int i = 0; i < ctxs.Count; i++)
                        {
                            if (ctxs[i].MaThuoc == ctx.MaThuoc)
                            {
                                datontaitrongds = true;
                                break;
                            }
                        }
                        if (!datontaitrongds)
                        {
                            ctxs.Add(ctx);
                            gc.DataSource = null;
                            gc.RefreshDataSource();
                            gc.DataSource = ctxs;
                            gc.RefreshDataSource();
                        }
                        else
                            clsHam.HienThi(Text, "Tthuốc/thiết bị này đã có trong danh sách");
                    }
                    else
                        clsHam.HienThi(Text, "Chưa có đơn giá nhập cho thuốc/thiết bị này");
                }
                catch { }
            }
            else
                clsHam.HienThi(Text, "Chưa có số Hóa đơn nhập");
        }

        private int soLuongConCuaThuoc(string mathuoc)
        {
            int soluong = 0;
            var tongnhap = db.CHITIETNHAPs.Where(x => x.MaThuoc == mathuoc).Sum(y => y.SoLuong);
            var tongxuat = db.CHITIETXUATs.Where(x => x.MaThuoc == mathuoc).Sum(y => y.SoLuong);
            if (tongxuat == null)
                tongxuat = 0; 
            soluong = (int)(tongnhap - tongxuat);
            if (soluong<0)
                soluong = 0;
            return soluong;
        }

        private void cbbKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                int makh = Int32.Parse(cbbKhachHang.EditValue.ToString());
                khachhang = db.KHACHHANGs.SingleOrDefault(x => x.MaKH == makh);
                if (khachhang != null)
                    tbDiaChi.Text = khachhang.DiaChi;
                else
                    tbDiaChi.Text = "";
            }
            catch { }
        }

        private void btLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxValid.SetValidationRule(cbbKhachHang, clsHam.ValidIsNotBlank("Chưa chọn khách hàng"));
            if (gv.RowCount == 0)
                clsHam.HienThi(Text, "Chưa có danh sách thuốc thiết bị sẽ nhập");
            else if (dxValid.Validate())
            {
                HDXUAT hdx = new HDXUAT();
                hdx.SoHDXuat = tbSoPhieu.Text;
                hdx.GhiChu = tbGhiChu.Text;
                hdx.MaNguoiDung = 2;
                hdx.BanLe = !banbuon;
                hdx.NgayXuat = DateTime.Parse(dtNgayLapPhieu.EditValue.ToString());
                hdx.XuatChoDonVi = cbbKhachHang.Text;
                db.HDXUATs.InsertOnSubmit(hdx);
                List<CHITIETXUAT> lctx = new List<CHITIETXUAT>();
                for (int i = 0; i < gv.RowCount; i++)
                {
                    var temp = gv.GetRow(i) as CHITIETXUATDVT;
                    CHITIETXUAT ctx = new CHITIETXUAT();
                    ctx.MaDonGia = temp.MaDonGia;
                    ctx.MaThuoc = temp.MaThuoc;
                    ctx.SoHDXuat = hdx.SoHDXuat;
                    ctx.SoLuong = temp.SoLuong;
                    lctx.Add(ctx);
                }
                if (lctx.Count > 0)
                    db.CHITIETXUATs.InsertAllOnSubmit(lctx);
                db.SubmitChanges();
                btLuu.Enabled = false;
                btIn.Enabled = true;
            }
        }

        private void btXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Chắc chắc xóa phiếu xuất " + tbSoPhieu.Text, "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var hdx = db.HDXUATs.SingleOrDefault(x => x.SoHDXuat == tbSoPhieu.Text);
                if (hdx != null)
                {
                    db.HDXUATs.DeleteOnSubmit(hdx);
                    db.SubmitChanges();
                }
                else
                    clsHam.HienThi(Text, "Không tồn tại phiếu xuất này trong hệ thống");
            }
        }

        private void btSua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxValid.SetValidationRule(cbbKhachHang, clsHam.ValidIsNotBlank("Chưa chọn khách hàng"));
            if (gv.RowCount == 0)
                clsHam.HienThi(Text, "Chưa có danh sách thuốc thiết bị sẽ nhập");
            else if (dxValid.Validate())
            {
                HDXUAT hdx = db.HDXUATs.SingleOrDefault(x => x.SoHDXuat == tbSoPhieu.Text);
                if (hdx != null)
                {
                    hdx.XuatChoDonVi = cbbKhachHang.Text;
                    hdx.GhiChu = tbGhiChu.Text;
                    hdx.BanLe = !banbuon;
                    List<CHITIETXUAT> lctx = db.CHITIETXUATs.Where(x => x.SoHDXuat == tbSoPhieu.Text).ToList();
                    db.CHITIETXUATs.DeleteAllOnSubmit(lctx);
                    db.SubmitChanges();
                    lctx = new List<CHITIETXUAT>();
                    for (int i = 0; i < gv.RowCount; i++)
                    {
                        var temp = gv.GetRow(i) as CHITIETXUATDVT;
                        CHITIETXUAT ctx = new CHITIETXUAT();
                        ctx.MaDonGia = temp.MaDonGia;
                        ctx.MaThuoc = temp.MaThuoc;
                        ctx.SoHDXuat = hdx.SoHDXuat;
                        ctx.SoLuong = temp.SoLuong;
                        lctx.Add(ctx);
                    }
                    if (lctx.Count > 0)
                        db.CHITIETXUATs.InsertAllOnSubmit(lctx);
                    db.SubmitChanges();
                }
            }
        }

        private void frmPhieuNhap_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case (Keys.F3):
                    seThuoc.ShowPopup();
                    break;
                case (Keys.F2):
                    cbbKhachHang.ShowPopup();
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btNapLai_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (db.HDNHAPs.Where(x => x.SoHDNhap == tbSoPhieu.Text).ToList().Count > 0)
            {

            }
        }

        private void btIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new rptPhieuXuat(tbSoPhieu.Text).ShowPreview();
        }

        private void gv_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "ThanhTien" && e.IsGetData)
                {
                    var a = gv.GetRow(e.ListSourceRowIndex) as CHITIETXUATDVT;
                    var b = db.GIATHUOCs.SingleOrDefault(x => x.MaDonGia == a.MaDonGia);
                    if (banbuon)
                        e.Value = a.SoLuong * b.GiaBanBuon;
                    else
                        e.Value = a.SoLuong * b.GiaBanLe;
                }
            }
            catch { }
        }
    }
}